package org.vectrics.company.client.module;


import java.awt.*;
import java.awt.event.*;
import java.util.Collection;
import javax.swing.*;
import javax.swing.event.*;
import javax.swing.JPanel;
import javax.swing.JSplitPane;
import org.apache.log4j.Logger;
import org.vectrics.VectricsException;
import org.vectrics.company.Company;
import org.vectrics.company.client.CompanyDataManager;
import org.vectrics.swing.GuiManager;
import org.vectrics.client.module.*;


//	mainSplitPane
//		TOP
//			messageScrollPane
//				listAndSearchPanel
//		BOTTOM
//			detailPanel
//				detailFIeldsPanel
//				

public class CompanyModulePanel extends ModulePanel implements ListSelectionListener {
    private transient static Logger log = Logger.getLogger(CompanyModulePanel.class);
    
    CompanyTableModel tableModel = new CompanyTableModel();
    JSplitPane mainSplitPane = new JSplitPane();
    JPanel listAndSearchPanel = new JPanel();
    JPanel detailFieldsPanel = new JPanel();
    JPanel detailPanel = new JPanel();
	JPanel bottomPanel = new JPanel();
	JPanel detailOptionsPanel = new JPanel();
	JPanel searchPanel = new JPanel();
    JTable userTable = new JTable(tableModel);
    FlowLayout paneLayout2 = new FlowLayout();
    JScrollPane messageScrollPane = new JScrollPane();
    JLabel nameSearchLabel = new JLabel();
    JPanel messageListPanel = new JPanel();
    JPanel blankPanel = new JPanel();
	Dimension detailTextMinSize = new Dimension(80, 18);
	JLabel companyNameText = null;
	JLabel addressText = null;
	JLabel companyCodeText = null;
	JLabel address2Text = null;
	JLabel cityStateZipText = null;
	JLabel phoneText = null;

    GridBagLayout gridBagLayout1 = new GridBagLayout();
	JTextField editSearchCompanyName = new JTextField();
	private static Color FIELD_COLOR = new Color(230, 230, 240);
	private Company selectedCompany = null;
	private int detailFieldCount = 0;
	private boolean displayAllCompanies = true;
	
		
    public CompanyModulePanel()  {
    	super();
        log.debug("Message Frame Constructor");
        try {
            init();
        }
        catch(Exception e) {
            log.error("Exception in MessageFrame constructor", e);
        }
    }
    
    private void init() throws Exception {
        log.info("init() - method to display controls on this frame");
		this.setBackground(Color.RED); 
		this.setLayout(new BoxLayout(this, BoxLayout.X_AXIS));       
		this.setFont(GuiManager.getInstance().getStandardFont());
		//this.setLayout(new BorderLayout());
		this.add(mainSplitPane);

		this.add(this.mainSplitPane, null);
		mainSplitPane.setDividerSize(10);
		mainSplitPane.setOrientation(JSplitPane.VERTICAL_SPLIT);
		//mainSplitPane.setLayout(new BorderLayout());
		

		searchPanel.setBorder(BorderFactory.createEtchedBorder());
		initSearchPanelComponents(searchPanel);

		messageScrollPane.setFont(GuiManager.getInstance().getStandardFont());
		messageScrollPane.setBorder(BorderFactory.createEtchedBorder());
		messageScrollPane.setToolTipText("");
		
		this.listAndSearchPanel.setLayout(new BoxLayout(listAndSearchPanel, BoxLayout.Y_AXIS));
		this.listAndSearchPanel.add(searchPanel);
		this.listAndSearchPanel.add(messageScrollPane);
		
        detailFieldsPanel.setBorder(BorderFactory.createEtchedBorder());
        detailFieldsPanel.setLayout(null);
        detailFieldsPanel.setPreferredSize(new Dimension(300, 100));
        detailFieldsPanel.setMaximumSize(new Dimension(300, 300));

        userTable.setFont(GuiManager.getInstance().getStandardFont());
        userTable.setAutoscrolls(false);
        userTable.setRowHeight(14);

        messageListPanel.setLayout(paneLayout2);
        messageListPanel.setMinimumSize(new Dimension(146, 300));
        messageListPanel.setPreferredSize(new Dimension(454, 490));


        messageScrollPane.getViewport().add(userTable, null);
        userTable.getSelectionModel().setSelectionMode(ListSelectionModel.SINGLE_SELECTION);
        userTable.getSelectionModel().addListSelectionListener(this);

		mainSplitPane.add(listAndSearchPanel, JSplitPane.TOP);
		mainSplitPane.add(bottomPanel, JSplitPane.BOTTOM);
		bottomPanel.setLayout(new BoxLayout(bottomPanel, BoxLayout.X_AXIS));
		bottomPanel.add(detailPanel);
        
        buildUserDetailsDisplay();
   }


	private JLabel makeDetailRow(JPanel panel, int rowNumber, String caption) {
		int rowHeight = 22;
		int leftInset = 4;
		int topInset = 4;
		
		int labelX = 0 + leftInset;
		int labelWidth = 100;
		int labelHeight = 18;
		
		int valueX = labelX + labelWidth + 10 + leftInset;
		int valueY = (rowNumber * 22) + topInset;
		int valueWidth = 120;
		int valueHeight = 18;
		
		JLabel label = new JLabel(); 
		label.setText(caption);
		label.setFont(GuiManager.getInstance().getStandardFont());
		label.setBounds(labelX, valueY, labelWidth, labelHeight);
		panel.add(label);
	
		JLabel fieldText = new JLabel();
		fieldText.setFont(GuiManager.getInstance().getStandardFont());
		fieldText.setBackground(FIELD_COLOR);
		fieldText.setBorder(BorderFactory.createEtchedBorder());
		fieldText.setBounds(valueX, valueY, valueWidth, valueHeight);
		panel.add(fieldText);
			
		return(fieldText);
	}

/*
	JButton makeButton(String label, int width, int height) {
		JButton button = new JButton();
		button.setMaximumSize(new Dimension(width, height));
		button.setMinimumSize(new Dimension(width, height));
		return(button);		
	}
*/
	
	private void buildUserDetailsDisplay() {
		//TableBuilder detailBuilder = new TableBuilder();		
		JButton moreDetailsButton = GuiManager.getInstance().createButton("More Details", 90, 20);
		moreDetailsButton.addActionListener(new java.awt.event.ActionListener() {
				public void actionPerformed(ActionEvent e) {
					moreDetailsButtonActionPerformed(e);
				}
			});
		
		
		JButton editDetailsButton = GuiManager.getInstance().createButton("Edit", 90, 20);
		editDetailsButton.addActionListener(new java.awt.event.ActionListener() {
				public void actionPerformed(ActionEvent e) {
					editUserButtonActionPerformed(e);
				}
			});
		
				
		detailOptionsPanel.setLayout(new BoxLayout(detailOptionsPanel, BoxLayout.Y_AXIS));
		detailOptionsPanel.add(moreDetailsButton);
		detailOptionsPanel.add(editDetailsButton);

		
		
		log.debug("creating first details grid");
		companyNameText = makeDetailRow(this.detailFieldsPanel, 0, "Company Name");
		companyCodeText = makeDetailRow(this.detailFieldsPanel, 1, "Code");
		addressText = makeDetailRow(this.detailFieldsPanel, 2, "Address");
		address2Text = makeDetailRow(this.detailFieldsPanel, 3, "Address 2");
		cityStateZipText = makeDetailRow(this.detailFieldsPanel, 4,  "City, State, Zip");
		phoneText = makeDetailRow(this.detailFieldsPanel, 5, "Home Phone");
		//detailBuilder.render(detailFieldsPanel);
		detailFieldsPanel.add(new JPanel());  // Add to bottom of panel to provide expansion area
		
		
		JPanel detailFieldsPanel2 = new JPanel();
		detailFieldsPanel2.setBorder(GuiManager.getInstance().getEtchedBorder());

		detailPanel.setLayout(new GridLayout(1, 3));
		detailPanel.setMinimumSize(new Dimension(100, 80));
		//TableBuilder detailSectionBuilder = new TableBuilder();	    
	    //Row detailRow = detailSectionBuilder.addRow();
		detailPanel.add(detailFieldsPanel);
		detailPanel.add(detailFieldsPanel2);
		detailPanel.add(detailOptionsPanel);
	   	//detailSectionBuilder.render(detailPanel);
	   	
		clearEventDetailDisplay();
	   	
	   	this.validate();
	}
	
	

    // Detect user selection changes with Message table.
    public void valueChanged(ListSelectionEvent iEvent)
    {
        log.debug("valueChanged() - method to detect user selection changes with message table.");
        ListSelectionModel selModel = (ListSelectionModel)iEvent.getSource();
        if (selModel.isSelectionEmpty()) {
            clearEventDetailDisplay();
        }
        else {
            int selIndex = selModel.getMinSelectionIndex();
            //System.out.println("Selected index = " + selIndex);
            
            Company company = tableModel.getElementAt(selIndex);
            displayCompanyDetails(company);
        };
    };

	private void initSearchPanelComponents(JPanel searchPanel) {
		log.debug("initSearchPanelComponents() - creating search edit boxes inside horiz sub panels");
		int searchPanelHeight = 25;
		
		searchPanel.setLayout(null);
		searchPanel.setMinimumSize(new Dimension(100, searchPanelHeight));
		searchPanel.setMaximumSize(new Dimension(4000, searchPanelHeight));
		searchPanel.setPreferredSize(new Dimension(300, searchPanelHeight));
		
		
		
		JLabel lastNameSearchLabel = new JLabel();
		nameSearchLabel.setFont(GuiManager.getInstance().getStandardFont());
		nameSearchLabel.setText("Name");
		int x = 10;
		int y = 2;
		int hSpace = 8;
		nameSearchLabel.setBounds(x, y, 60, 18);
		x += nameSearchLabel.getSize().width;
		x += hSpace;
		searchPanel.add(nameSearchLabel);
		editSearchCompanyName.setText("");
		editSearchCompanyName.setBounds(x, y, 140, 18);
		x += editSearchCompanyName.getSize().width;
		x += 2 * hSpace;
		searchPanel.add(editSearchCompanyName);		


		JButton searchButton = GuiManager.getInstance().createButton("Search", 90, 20);
		Dimension size = searchButton.getPreferredSize();
		searchButton.setBounds(x, y, size.width, size.height);
		searchButton.addActionListener(new java.awt.event.ActionListener() {
				public void actionPerformed(ActionEvent e) {
					searchButtonActionPerformed(e);
				}
			});
		searchPanel.add(searchButton);
	}


    private void clearEventDetailDisplay()
    {
        companyNameText.setText(" ");
        companyCodeText.setText(" ");
        addressText.setText(" ");
        address2Text.setText(" ");
		cityStateZipText.setText(" ");
		phoneText.setText(" ");
    };


	

    private void displayCompanyDetails(Company company) {
    	
        if (company != null) {
        	clearEventDetailDisplay();
        	selectedCompany = company;
			if (company != null) {
	            companyNameText.setText(company.getName());
	            companyCodeText.setText(company.getReferenceId());
	            phoneText.setText(company.getPhone());
            }
			else {
			}
        } 
        else {
			log.debug("displayEventDetails() - clearing field display");
			selectedCompany = null;
			//clearEventDetailDisplay();
        	disableDetailOptions();
        }
        bottomPanel.doLayout();
		
		companyNameText.validate();
		address2Text.validate();
		detailFieldsPanel.validate();
		this.repaint();
		this.validateTree();
    };


	private void enableDetailOptions() {
	}

	private void disableDetailOptions() {
		
	}


	/**
	 * Search button clicked, get users which match criteria.
	 */
	protected void searchButtonActionPerformed(ActionEvent e) {
		try {
			log.info("searchButtonActionPerformed() - Ok button pressed");
			CompanyDataManager companyMgr = CompanyDataManager.getInstance();
			String companyName = this.editSearchCompanyName.getText();
			Collection companies = companyMgr.getCompaniesNameMatch(companyName);            
			this.tableModel.setCompanyList(companies);
			log.info("searchButtonActionPerformed() - New server connection created");
		}
		catch (Exception ex) {
			log.error("Exception searching after button pressed: ", ex);
		};
	}

	/**
	 * Search button clicked, get users which match criteria.
	 */
	protected void moreDetailsButtonActionPerformed(ActionEvent e) {
		try {
			log.debug("details button pressed");
			displayCompanyDetails(selectedCompany);
		}
		catch (Exception ex) {
			log.error("Exception searching after button pressed: ", ex);
		};
	}

	protected void editUserButtonActionPerformed(ActionEvent e) {
		editSelectedUser();
	}

	private void editSelectedUser() {
		//UserEditFrame form = new UserEditFrame();
		Class moduleClass = CompanyEditModule.class;
		try {
			CompanyEditModule module = (CompanyEditModule)this.findModule(moduleClass);
			module.editCompany(selectedCompany);
		}
		catch (UnknownModuleException ue) {
			log.error("UnknownModuleException while attempting to switch to user edit module", ue);
		}
	}
        
	public void displayAllCompanies() {
		setDisplayAllCompanies(true);
		CompanyDataManager companyMgr = CompanyDataManager.getInstance();
		Collection companies = companyMgr.findAllCompanies();            
		this.tableModel.setCompanyList(companies);
	}
	
	/**
	 * @return Returns the displayAllCompanies.
	 */
	public boolean getDisplayAllCompanies() {
		return displayAllCompanies;
	}

	/**
	 * @param displayAllCompanies The displayAllCompanies to set.
	 */
	public void setDisplayAllCompanies(boolean displayAllCompanies) {
		this.displayAllCompanies = displayAllCompanies;
	}

}